import * as vscode from 'vscode';
import * as path from 'path';

/**
 * 获取指定目录下的所有Markdown文件
 */
export async function getAllMarkdownFiles(directoryPath: string): Promise<vscode.Uri[]> {
    try {
        const files = await vscode.workspace.findFiles(
            new vscode.RelativePattern(directoryPath, '**/*.md'),
            '**/node_modules/**'
        );
        return files;
    } catch (error) {
        handleError(error as Error);
        return [];
    }
}

/**
 * 按最后修改时间排序文件（降序）
 */
export async function sortFilesByModifiedTime(files: vscode.Uri[]): Promise<vscode.Uri[]> {
    try {
        const fileStats = await Promise.all(
            files.map(async (file) => {
                const stat = await vscode.workspace.fs.stat(file);
                return { file, mtime: stat.mtime };
            })
        );

        return fileStats
            .sort((a, b) => b.mtime - a.mtime)
            .map(item => item.file);
    } catch (error) {
        handleError(error as Error);
        return files;
    }
}

/**
 * 获取文件的第一行内容
 */
export async function getFirstLine(uri: vscode.Uri): Promise<string> {
    try {
        const document = await vscode.workspace.openTextDocument(uri);
        return document.lineAt(0).text;
    } catch (error) {
        handleError(error as Error);
        return path.basename(uri.fsPath);
    }
}

/**
 * 检查文件是否存在
 */
export async function fileExists(uri: vscode.Uri): Promise<boolean> {
    try {
        await vscode.workspace.fs.stat(uri);
        return true;
    } catch {
        return false;
    }
}

function handleError(error: Error): void {
    console.error('Error in fileUtils:', error);
    vscode.window.showErrorMessage(`Error: ${error.message}`);
}